const generatorImage = require("./generator-image.js");
const formatTime = date => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  return (
    [year, month, day].map(formatNumber).join("/") +
    " " +
    [hour, minute, second].map(formatNumber).join(":")
  );
};
const logger = (name, str) => {
  console.log("logger: ", name, str);
  http("/v1/client/log.do", {
    name: JSON.stringify(name),
    str: JSON.stringify(str),
  })
    .then()
    .catch();
};
const formatNumber = n => {
  n = n.toString();
  return n[1] ? n : "0" + n;
};

const http = (url = "", data = {}, file = {}) => {
  let initUrl = "";
  if (/^https?/.test(url)) {
    initUrl = url;
  } else {
    initUrl = "https://mobile.kuaimp.com" + url;
  }
  return new Promise((resolve, reject) => {
    if (file.name) {
      wx.uploadFile({
        url: initUrl,
        filePath: file.path,
        name: file.name,
        formData: resolveData(data),
        success(res) {
          console.log(url + ":");
          console.log(resolveData(data));
          console.log(JSON.parse(res.data));
          resolve(JSON.parse(res.data));
        },
        error(res) {
          netError();
          reject(res);
        },
      });
    } else {
      wx.request({
        method: "POST",
        url: initUrl,
        data: resolveData(data),
        success(res) {
          if (url !== "/v1/client/log.do") {
            console.log(url + ":");
            console.log(resolveData(data));
            console.log(res.data);
          }

          resolve(res.data);
        },
        error(res) {
          netError();
          reject(res);
        },
      });
    }
  });
};

const systemInfoRes = wx.getSystemInfoSync();
const systemInfo = [
  systemInfoRes.brand,
  systemInfoRes.model,
  systemInfoRes.version,
  systemInfoRes.system,
  systemInfoRes.platform,
].join("/");

const resolveData = (data = {}) => {
  const uuid = wx.getStorageSync("uuid") || "";
  const userId = wx.getStorageSync("userId") || "";
  const token = wx.getStorageSync("token") || "";
  const realData = Object.assign(
    {},
    {
      // uuid,
      token,
      userId,
      systemInfo,
    },
    data,
  );
  return realData;
};
const isLogin = () => {
  return !!wx.getStorageSync("userId") && !!wx.getStorageSync("token");
};

const netError = () => {
  wx.showToast({
    icon: "none",
    title: "网络异常",
  });
};
const message = msg => {
  wx.showToast({
    icon: "none",
    title: "" + msg,
  });
};
const serializeUrl = data => {
  let info = "";
  for (let i in data) {
    if (/string/i.test(Object.prototype.toString.call(data[i]))) {
      info = info + `&${i}=${data[i]}`;
    }
    if (data[i] === null) {
      info = info + `&${i}=`;
    }
  }
  return info.slice(1);
};

const updateMyCards = () => {
  return new Promise((resolve, reject) => {
    ajax("/v1/bcs/queryUserCards.do")
      .then(res => {
        if (res.code === "000000") {
          let _res = res;
          getApp().globalData["myCards"] = res.data.userCards;
          resolve(res);
        } else {
          console.log("获取用户名片列表失败");
          reject({ errMsg: "获取用户名片列表失败" });
        }
      })
      .catch(res => {
        console.log("获取用户名片列表失败： 网络错误");
        reject({ errMsg: "获取用户名片列表失败： 网络错误" });
      });
  });
};
const wxLogin = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 code
        ajax("/v1/cif/loginByCode.do", {
          code: res.code,
        })
          .then(res => {
            if (res.code === "000000") {
              wx.setStorageSync("token", res.data.token);
              wx.setStorageSync("userId", res.data.userId);
              getApp().globalData["userId"] = res.data.userId;
              getApp().globalData["token"] = res.data.token;
              resolve();
            } else {
              message(res.message || "登录失败");
              console.log(res.message || "登录失败");
              reject(res);
            }
          })
          .catch(res => {
            console.log("登录时，网络错误");
            reject(res);
          });
      },
    });
  });
};
const preCheck = update => {
  return new Promise((resolve, reject) => {
    if (update) {
    } else {
    }
    updateMyCards()
      .then(res => {
        resolve();
      })
      .catch(err => {});
  });
};
const preGet = () => {
  return new Promise((resolve, reject) => {
    updateMyCards()
      .then(res => {
        resolve(res);
      })
      .catch(err => {
        reject();
      });
  });
};
const defaultShare = {
  onReady() {
    wx.showShareMenu();
  },
  onShareAppMessage(res) {
    return {
      title: "快名片助手-微信小程序",
      path: "/pages/index/index",
      imageUrl: "/static/images/logo.png",
    };
  },
};
const successCallback = () => {};
const ajax = (url = "", data = {}, file = {}, success = successCallback) => {
  let initUrl = "";
  if (/^https?/.test(url)) {
    initUrl = url; // 这里是测试url
  } else {
    initUrl = "https://mobile.kuaimp.com" + url;
  }
  return new Promise((resolve, reject) => {
    if (file.name) {
      wx.uploadFile({
        url: initUrl,
        filePath: file.path,
        name: file.name,
        formData: resolveData(data),
        success(res) {
          console.log(url + ":");
          console.log(resolveData(data));
          console.log(JSON.parse(res.data));
          if (res.data.code === "001101") {
            // token过期
            wxLogin()
              .then(res => {
                console.log(url, data, file, success);
                return ajax(url, data, file, success)
                  .then(res => {
                    // 重新登录获取token后，直接返回data内容即可，不需要再判断了
                    resolve(res);
                  })
                  .catch(err => {
                    reject(err);
                  });
              })
              .catch(err => {
                reject(res);
              });
          } else {
            resolve(JSON.parse(res.data));
          }
        },
        error(res) {
          reject(res);
        },
      });
    } else {
      wx.request({
        method: "POST",
        url: initUrl,
        data: resolveData(data),
        success(res) {
          console.log(url + ":");
          console.log(resolveData(data));
          console.log(res.data);

          if (res.data.code === "001101") {
            // token过期
            wxLogin()
              .then(res => {
                console.log(url, data, file, success);
                return ajax(url, data, file, success)
                  .then(res => {
                    // 重新登录获取token后，直接返回data内容即可，不需要再判断了
                    resolve(res);
                  })
                  .catch(err => {
                    reject(err);
                  });
              })
              .catch(err => {
                reject(res);
              });
          } else {
            resolve(res.data);
          }
        },
        error(res) {
          reject(res);
        },
      });
    }
  });
};
const test = params => {
  params.success();
};
module.exports = {
  preGet,
  test,
  ajax,
  defaultShare,
  preCheck,
  wxLogin,
  formatTime: formatTime,
  resolveData,
  http,
  isLogin,
  netError,
  Promise,
  message,
  serializeUrl,
  generatorImage,
  updateMyCards,
  logger,
};
